from typing import Any
from io import BytesIO
from django.shortcuts import render
from django.http.response import JsonResponse
from django.shortcuts import HttpResponse
from django.views import View
from web.forms.account import RegisterForm
from web.forms.account import MobilePhoneForm
from web.forms.account import SmsLoginForm
from web.forms.account import LoginForm
from web.utils.checkcode import get_image
import uuid
import datetime
from web import models

class RegisterView(View):
    '''
    用户注册
    '''
    def get(self, request: Any) -> HttpResponse:
        form = RegisterForm()
        return render(request, 'account/register.html', {'form': form})

    def post(self,request:Any)->JsonResponse:

        form = RegisterForm(request.POST)
        if form.is_valid():
            #保存注册用户
            try:
                instance=form.save()
                #为注册用户生成免费版的交易记录
                pricepolicy=models.PricePolicy.objects.filter(category=1).first()
                models.Transaction.objects.create(user=instance,
                                                  order=str(uuid.uuid4()),
                                                  status=2,
                                                  price_policy=pricepolicy,
                                                  start_datetime=datetime.datetime.now(),
                                                  price=0,
                                                  count=0
                                                  )
                return JsonResponse({'code':200,'data':'/api/login/','error':''})
            except Exception as e:
                return JsonResponse({'code': 400, 'data': '', 'error': form.errors})
        else:
            return JsonResponse({'code':400,'data':'','error':form.errors})
class SendSmsView(View):
    '''
    处理短信验证码
    '''
    def get(self, request: Any) -> JsonResponse:
        #获取手机号
        # phone=request.GET.get('phone')
        form=MobilePhoneForm(request=request,data=request.GET)
        if form.is_valid():

            return JsonResponse({'code': '200', 'data': 'ok', 'error': ''})
        else:
            return JsonResponse({'code': '400', 'data': '', 'error': form.errors})


class SmsLoginView(View):
    def get(self,request):
        form=SmsLoginForm()
        return render(request,'account/smsLogin.html',{'form':form})

    def post(self,request):

        form=SmsLoginForm(request.POST)
        if form.is_valid():
            #把用户信息存入session中
            userObj=models.UserInfo.objects.filter(mobile_phone=form.cleaned_data.get('mobile_phone')).first()
            request.session['user']={'id':userObj.id,
                                     'username':userObj.username,
                                     'mobile_phone':userObj.mobile_phone}
            request.session.set_expiry(60 * 60 * 24 * 7)
            return JsonResponse({'code': '200', 'data': 'ok', 'error': ''})
        else:
            return JsonResponse({'code': '400', 'data': '', 'error': form.errors})

class LoginView(View):

    def get(self,request):
        form=LoginForm(request=request)

        return render(request,'account/login.html',{'form':form})
    def post(self,request):
        form=LoginForm(request=request,data=request.POST)
        if form.is_valid():
            username=form.cleaned_data.username
            id=form.cleaned_data.id
            mobile_phone=form.cleaned_data.mobile_phone
            request.session['user'] = {'id': id, 'username': username,'mobile_phone': mobile_phone}
            request.session.set_expiry(60*60*24*7)
            return JsonResponse({'code':200,'data':'/api/index/'})
        else:
            return JsonResponse({'code':400,'data':'','error':form.errors})


class CheckCodeView(View):
    '''
    图片验证码
    '''
    def get(self,request):
        img, code = get_image()
        request.session['code']=code
        #主动修改session的过期时间为60s
        request.session.set_expiry(60)
        stream=BytesIO()
        img.save(stream,'png')
        # return JsonResponse({'code':200,'data':stream.getvalue(),'error':''})
        return HttpResponse(stream.getvalue())


class LogoutView(View):

    def  get(self,request):
        request.session['user']=None
        request.tracer=None
        return JsonResponse({'code':200,'data':'/api/index'})